// app.js
import './utils/http'

App({
    globalData: {},
    onLaunch() {
        this.getToken()
        this.getUserInfo()
        this.globalData.userId = null
        this.globalData.isLogin = false
    },
    
    getToken() {
        // 读取本地token
        this.token = wx.getStorageSync('token')
    },
    setToken(key, token) {
        // 存入应用实例
        this[key] = token
        // 存入本地
        wx.setStorageSync(key, token)
    },
    // 获取用户信息判断用户是否登录
    async getUserInfo() {
        const res = await wx.http.get('/user/info')
        if(res.data.status !== 401) {
            const userId = res.data.data.userInfo.user_id
                if(userId) {
                    this.setUserLoginStatus(userId)
                }
        } else {
            this.setUserLoginStatus('')
        }
    },
    // 更新登录状态
    setUserLoginStatus(userId) {
        this.globalData.userId = userId
        this.globalData.isLogin = !!userId
    }
})
